package cn.yuanqiao.archive.danganzhengli.service.impl;


import cn.yuanqiao.activiti.domain.ActivitiPackage;
import cn.yuanqiao.activiti.service.RemoteActivitiService;
import cn.yuanqiao.archive.appManager.domain.*;
import cn.yuanqiao.archive.appManager.mapper.*;
import cn.yuanqiao.archive.appManager.service.ITenantSysConfigService;
import cn.yuanqiao.archive.appManager.service.ITenantSysDictTypeService;
import cn.yuanqiao.archive.danganzhengli.domain.OnlinePackageDa;
import cn.yuanqiao.archive.danganzhengli.domain.YqdaOnlineReception;
import cn.yuanqiao.archive.danganzhengli.mapper.OnlinePackageDaMapper;
import cn.yuanqiao.archive.danganzhengli.mapper.YqdaOnlineReceptionMapper;
import cn.yuanqiao.archive.danganzhengli.service.IOnlineReceptionService;
import cn.yuanqiao.archive.management.utils.StringUtils;
import cn.yuanqiao.archive.uploadfile.service.impl.FileService;
import cn.yuanqiao.archive.webservice.service.receiveFeedbackWebService;
import cn.yuanqiao.archive.webservice.utils.XMLtoJsonUtils;
import cn.yuanqiao.archive.wenjianzhengli.mapper.TenantItemFolderMapper;
import cn.yuanqiao.archive.wenjianzhengli.mapper.TenantYqdaFolderMapper;
import cn.yuanqiao.common.core.domain.R;
import cn.yuanqiao.common.exception.ServiceException;
import cn.yuanqiao.common.utils.ListUtils;
import cn.yuanqiao.common.utils.SnowflakeIdGenerator;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import org.apache.commons.io.FileUtils;
import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class OnlineReceptionServiceImpl implements IOnlineReceptionService {
    private final Logger logger = LoggerFactory.getLogger(OnlineReceptionServiceImpl.class);
    @Autowired
    private YqdaOnlineReceptionMapper onlineReceptionMapper;
    @Autowired
    private ITenantSysConfigService sysConfigService;
    @Autowired
    private TenantCategoryMapper categoryMapper;
    @Autowired
    private TenantYqItemMapper yqItemMapper;
    @Autowired
    private TenantMdataListMapper mdataListMapper;
    @Autowired
    private TenantYqFolderMapper yqFolderMapper;
    @Autowired
    private TenantItemFolderMapper itemFolderMapper;
    @Autowired
    private ArchiveMapper archiveMapper;
    @Autowired
    private TenantYqdaMapper yqdaMapper;
    @Autowired
    private TenantYqdaFolderMapper yqdaFolderMapper;
    @Autowired
    private TenantSysConfigMapper tenantSysConfigMapper;
    @Autowired
    private TenantYqdaDocumentMapper tenantYqdaDocumentMapper;
    @Autowired
    private RemoteActivitiService activitiService;
    @Autowired
    private ITenantSysDictTypeService sysDictTypeService;
    @Autowired
    private OnlinePackageDaMapper onlinePackageDaMapper;

    @Override
    @Transactional
    public JSONObject saveArchivePackage(File file, Long id, Long categoryId, String tenantCode) throws Exception {
        YqdaOnlineReception onlineReception = new YqdaOnlineReception();
        onlineReception.setCategoryId(categoryId);
        onlineReception.setId(id);
        onlineReceptionMapper.updateYqdaOnlineReception(onlineReception);
        String charset = sysConfigService.selectConfigByCode("package_charset", tenantCode);
        if (StringUtils.isNULLString(charset)) {
            charset = "UTF-8";
        }
        String unzipPath = file.getParent() + File.separator + (file.getName().substring(0, file.getName().lastIndexOf(".")));   //解压文件路径
        FileService.decompress(file.getAbsolutePath(), unzipPath, charset);  //解压文件
        JSONObject msg = new JSONObject();
        traverseFiles(new File(unzipPath), id, categoryId, msg, tenantCode);
        return msg;
    }

    private void traverseFiles(File directory, Long id, Long categoryId, JSONObject msg, String tenantCode) throws Exception {
        if (directory.isDirectory()) {
            File[] files = directory.listFiles();
            if (files != null) {
                for (File file : files) {
                    traverseFiles(file, id, categoryId, msg, tenantCode);
                }
            }
        } else {
            //文件类型
            if (directory.getName().toLowerCase().endsWith(".xml")) {
                analysisArchive(directory, id, categoryId, msg, tenantCode);
            }
        }
    }

    private void analysisArchive(File xmlFile, Long id, Long categoryId, JSONObject msg, String tenantCode) throws Exception {
        //通过档号判断门类
        JSONObject archiveData = XMLtoJsonUtils.startXMLToJSON(xmlFile);  //xml 文件解析成 JSON格式
        logger.info(archiveData.toJSONString());
        //档案类型
        /*String archiveType = archiveData.getJSONObject("被签名对象").getJSONObject("封装内容").getJSONObject("档案实体块").getString("聚合层次");
        JSONObject dh = archiveData.getJSONObject("被签名对象").getJSONObject("封装内容").getJSONObject("档案实体块").getJSONObject("档号");
        String qzh = dh.getString("全宗号");
        String code = dh.getString("档案门类");
        Integer type = null;
        Boolean xmBl =  archiveData.getJSONObject("被签名对象").getJSONObject("封装内容").getJSONObject("档案实体块").getJSONObject("内容描述").containsKey("项目层");
        if(xmBl){
            type = 3;
        }else if("组卷".equals(archiveType)){
            type = 1;
        }else if("文件".equals(archiveType)){
            type = 0;
        }
        TenantCategory selectCategory = new TenantCategory();
        selectCategory.setType(type);
        selectCategory.setCode(code);
        selectCategory.setFondsCode(qzh);
        selectCategory.setTableName(tenantCode+TenantCategory.BIGTABLENAME);*/
        //确定门类
        TenantCategory category = categoryMapper.selectTenantCategoryByID(categoryId, tenantCode + TenantCategory.BIGTABLENAME);
        if (category != null) {
            //TenantCategory category = categoryList.get(0);
            Long itemId = SnowflakeIdGenerator.generateId();
            TenantMdataList mdataListSelect = new TenantMdataList();
            mdataListSelect.setTableName(tenantCode + TenantMdataList.BIGTABLENAME);
            List<TenantMdataList> mdataLists = mdataListMapper.selectTenantMdataListListByCategoryId(mdataListSelect, category.getId(), new TenantCategory().getTableName());
            if (category.getType() == 3) {
                //项目层入库
                JSONObject xmJson = archiveData.getJSONObject("被签名对象").getJSONObject("封装内容").getJSONObject("档案实体块").getJSONObject("内容描述")
                        .getJSONObject("项目层");
                Map<String, String> map = new HashMap<>();
                for (TenantMdataList mdataList : mdataLists) {
                    if (mdataList.getType() == 3 && xmJson.containsKey(mdataList.getFieldCaption())) {
                        if (mdataList.getShowType() == 5) {
                            map.put(mdataList.getFieldName(), getDictVal(mdataList.getFieldName(), xmJson.getString(mdataList.getFieldCaption())));
                        } else {
                            map.put(mdataList.getFieldName(), xmJson.getString(mdataList.getFieldCaption()));
                        }
                    }
                }
                map.put("STATE", "13");
                map.put("IS_DEL", "0");
                map.put("JS_TYPE", "5");
                //查询是否已有这个项目
                Long oldId = archiveMapper.getIdByMap(map, category.getItemTableName());
                if (oldId == null) {
                    map.put("ITEM_ID", String.valueOf(itemId));
                    map.put("SUB_TABLE_NAME", category.getItemTableName());
                    TenantYqItem yqItem = new TenantYqItem();
                    yqItem.setColNames(map);
                    yqItem.setTableName(tenantCode + TenantYqItem.BIGTABLENAME);
                    yqItemMapper.insertItem(yqItem);

                    yqItem.setTableName(category.getItemTableName());
                    map.remove("ITEM_ID");
                    map.remove("SUB_TABLE_NAME");
                    map.put("ID", String.valueOf(itemId));
                    yqItem.setColNames(map);
                    yqItemMapper.insertItemDisperse(yqItem);
                    //添加记录
                    OnlinePackageDa onlinePackageDa = new OnlinePackageDa();
                    onlinePackageDa.setDaId(itemId);
                    onlinePackageDa.setDaType(3);
                    onlinePackageDa.setOnlineReceptionId(id);
                    onlinePackageDa.setState(0);
                    onlinePackageDa.setCategoryId(category.getId());
                    onlinePackageDa.setTableName(tenantCode + OnlinePackageDa.BIGTABLENAME);
                    onlinePackageDaMapper.insterOnlinePackageDa(onlinePackageDa);
                } else {
                    itemId = oldId;
                }
            }
            //处理卷层
            Long folderId = SnowflakeIdGenerator.generateId();
            if (category.getType() == 3 || category.getType() == 1) {
                JSONObject juanJson = archiveData.getJSONObject("被签名对象").getJSONObject("封装内容").getJSONObject("档案实体块").getJSONObject("内容描述");
                Map<String, String> map = new HashMap<>();
                for (TenantMdataList mdataList : mdataLists) {
                    if (mdataList.getType() == 1 && juanJson.containsKey(mdataList.getFieldCaption())) {
                        if (mdataList.getShowType() == 5) {
                            map.put(mdataList.getFieldName(), getDictVal(mdataList.getFieldName(), juanJson.getString(mdataList.getFieldCaption())));
                        } else {
                            map.put(mdataList.getFieldName(), juanJson.getString(mdataList.getFieldCaption()));
                        }
                    }
                }
                map.put("STATE", "13");
                map.put("IS_DEL", "0");
                map.put("JS_TYPE", "5");
                map.put("FOLDER_ID", String.valueOf(folderId));
                map.put("SUB_TABLE_NAME", category.getFolderTableName());
                TenantYqFolder yqFolder = new TenantYqFolder();
                yqFolder.setTableName(tenantCode + TenantYqFolder.BIGTABLENAME);
                yqFolder.setColNames(map);
                yqFolderMapper.insertYqFolder(yqFolder);

                map.remove("FOLDER_ID");
                map.remove("SUB_TABLE_NAME");
                map.put("ID", String.valueOf(folderId));
                yqFolder.setColNames(map);
                yqFolder.setTableName(category.getFolderTableName());
                yqFolderMapper.insertYqFolderDisperse(yqFolder);
                //添加记录
                OnlinePackageDa onlinePackageDa = new OnlinePackageDa();
                onlinePackageDa.setDaId(folderId);
                onlinePackageDa.setDaType(1);
                onlinePackageDa.setOnlineReceptionId(id);
                onlinePackageDa.setState(0);
                onlinePackageDa.setCategoryId(category.getId());
                onlinePackageDa.setTableName(tenantCode + OnlinePackageDa.BIGTABLENAME);
                onlinePackageDaMapper.insterOnlinePackageDa(onlinePackageDa);
                //添加关联关系
                if (category.getType() == 3) {
                    TenantItemFolder itemFolder = new TenantItemFolder();
                    itemFolder.setFolderId(folderId);
                    itemFolder.setItemId(itemId);
                    itemFolder.setTableName(tenantCode + TenantItemFolder.BIGTABLENAME);
                    itemFolderMapper.addItemFolder(itemFolder);
                }
            }
            //处理件层
            JSONArray jianArray = new JSONArray();
            if (category.getType() == 0) {
                jianArray.add(archiveData.getJSONObject("被签名对象").getJSONObject("封装内容").getJSONObject("档案实体块").getJSONObject("内容描述"));
            } else {
                //判断没有卷内件的状况
                if( archiveData.getJSONObject("被签名对象").getJSONObject("封装内容").getJSONObject("档案实体块").getJSONObject("内容描述").getJSONObject("件层集").containsKey("件层")){
                    jianArray = archiveData.getJSONObject("被签名对象").getJSONObject("封装内容").getJSONObject("档案实体块").getJSONObject("内容描述").getJSONObject("件层集").getJSONArray("件层");
                }
            }
            TenantSysConfig config = new TenantSysConfig();
            config.setTenantCode(tenantCode);
            config.setConfigKey("YQ_MNT");
            String baseDir = tenantSysConfigMapper.selectConfig(config).getConfigValue();  //保存位置
            for (int i = 0; i < jianArray.size(); i++) {
                JSONObject jian = jianArray.getJSONObject(i);
                Long daId = SnowflakeIdGenerator.generateId();
                Map<String, String> map = new HashMap<>();
                for (TenantMdataList mdataList : mdataLists) {
                    if (mdataList.getType() == 0 && jian.containsKey(mdataList.getFieldCaption())) {
                        if (mdataList.getShowType() == 5) {
                            map.put(mdataList.getFieldName(), getDictVal(mdataList.getFieldName(), jian.getString(mdataList.getFieldCaption())));
                        } else {
                            map.put(mdataList.getFieldName(), jian.getString(mdataList.getFieldCaption()));
                        }
                    }
                }

                if (StringUtils.isNULLString(map.get("DH"))) {
                    throw new ServiceException("四性检测完成，但件层缺少“DH”字段！");
                }
                String jianDH = map.get("DH");
                map.put("STATE", "13");
                map.put("IS_DEL", "0");
                map.put("JS_TYPE", "5");
                map.put("DA_ID", String.valueOf(daId));
                map.put("SUB_TABLE_NAME", category.getFileTableName());
                TenantYqda yqda = new TenantYqda();
                yqda.setColNames(map);
                yqda.setTableName(tenantCode + TenantYqda.BIGTABLENAME);
                yqdaMapper.insertYqda(yqda);

                map.remove("DA_ID");
                map.remove("SUB_TABLE_NAME");
                map.put("ID", String.valueOf(daId));
                yqda.setColNames(map);
                yqda.setTableName(category.getFileTableName());
                yqdaMapper.insertYqdaDisperse(yqda);
                //添加记录
                OnlinePackageDa onlinePackageDa = new OnlinePackageDa();
                onlinePackageDa.setDaId(daId);
                onlinePackageDa.setDaType(0);
                onlinePackageDa.setOnlineReceptionId(id);
                onlinePackageDa.setState(0);
                onlinePackageDa.setCategoryId(category.getId());
                onlinePackageDa.setTableName(tenantCode + OnlinePackageDa.BIGTABLENAME);
                onlinePackageDaMapper.insterOnlinePackageDa(onlinePackageDa);
                //添加关联关系
                if (category.getType() != 0) {
                    TenantYqdaFolder yqdaFolder = new TenantYqdaFolder();
                    yqdaFolder.setDaId(daId);
                    yqdaFolder.setFolderId(folderId);
                    yqdaFolder.setTableName(tenantCode + TenantYqdaFolder.BIGTABLENAME);
                    yqdaFolderMapper.addYqdaFolder(yqdaFolder);
                }

                //解析电子文件层
                JSONArray eFileJson = null;
                /*if(category.getType() !=0){
                    eFileJson = jian.getJSONObject("文件数据集").getJSONArray("文件数据");
                }else {
                    eFileJson = jian.getJSONObject("文件数据集").getJSONArray("文件数据");
                }*/
                if (jian.getJSONObject("文件数据集") != null) {
                    eFileJson = objecttoarray(jian.getJSONObject("文件数据集").get("文件数据"));
                    for (int j = 0; j < eFileJson.size(); j++) {
                        JSONObject eFileObject = eFileJson.getJSONObject(j).getJSONObject("文档").getJSONObject("文档数据").getJSONObject("编码").getJSONObject("电子属性");
                        map = new HashMap<>();
                        for (TenantMdataList mdataList : mdataLists) {
                            if (mdataList.getType() == 2 && eFileObject.containsKey(mdataList.getFieldCaption())) {
                                if (mdataList.getShowType() == 5) {
                                    map.put(mdataList.getFieldName(), getDictVal(mdataList.getFieldName(), eFileObject.getString(mdataList.getFieldCaption())));
                                } else {
                                    map.put(mdataList.getFieldName(), eFileObject.getString(mdataList.getFieldCaption()));
                                }
                            }
                        }
                        String filePath = extractPath(category, daId);  //存储的相对路径
                        String fileName = eFileObject.getString("文件实际名称");
                        if (!eFileObject.containsKey("文件实际名称")) {
                            throw new ServiceException("四性检测完成，但电子件层缺少“文件实际名称”！");
                        }
                        if (!eFileObject.containsKey("文件类型")) {
                            throw new ServiceException("四性检测完成，但电子件层缺少“文件类型”！");
                        }
                        File xmlPath = null;
                        if (category.getType() != 0) {
                            xmlPath = new File(xmlFile.getParent() + File.separator + jianDH + File.separator + fileName);  //归档包电子文件路径
                        } else {
                            xmlPath = new File(xmlFile.getParent() + File.separator + fileName);  //归档包电子文件路径
                        }
                        String absPath = getAbsoluteFile(baseDir + filePath, fileName).getAbsolutePath();  //保存文件位置  绝对路径
                        if(!xmlPath.exists()){
                            throw new ServiceException("电子文件不存在！！");
                        }
                        FileUtils.copyFile(xmlPath, new File(absPath));  //复制文件
                        map.put("PATH", filePath + fileName);
                        map.put("DOC_MNT", baseDir);
                        map.put("IS_INDEX", "0");
                        map.put("IS_DEL", "0");
                        map.remove("CREATE_BY");
                        TenantYqdaDocument saveDocument = new TenantYqdaDocument();
                        saveDocument.setColNames(map);
                        saveDocument.setTableName(category.getEfileTableName());
                        saveDocument.setDocId(SnowflakeIdGenerator.generateId());
                        saveDocument.setConTableId(daId);
                        tenantYqdaDocumentMapper.insertDocument(saveDocument);
                        //添加记录
                        OnlinePackageDa onlinePackageDaDoc = new OnlinePackageDa();
                        onlinePackageDaDoc.setDaId(daId);
                        onlinePackageDaDoc.setDaType(0);
                        onlinePackageDaDoc.setOnlineReceptionId(id);
                        onlinePackageDaDoc.setState(0);
                        onlinePackageDaDoc.setCategoryId(category.getId());
                        onlinePackageDaDoc.setTableName(tenantCode + OnlinePackageDa.BIGTABLENAME);
                        onlinePackageDaMapper.insterOnlinePackageDa(onlinePackageDaDoc);
                    }
                }
            }
            /*YqdaOnlineReception onlineReception = new YqdaOnlineReception();
            onlineReception.setCategoryId(category.getId());
            onlineReception.setId(id);
            onlineReceptionMapper.updateYqdaOnlineReception(onlineReception);*/
        } else {
            msg.put("msg", "没有匹配到门类信息！");
        }
    }

    /**
     * 字典项
     *
     * @param fieldName
     * @param dict
     * @return
     */
    private String getDictVal(String fieldName, String dict) {
        String DictVal = "";
        Boolean bl = false;
        List<TenantSysDictData> list = sysDictTypeService.selectDictDataByType(fieldName);
        if (list != null && list.size() > 0) {
            if (dict != null) {
                for (TenantSysDictData dictData : list) {
                    if (dict.equals(dictData.getDictLabel())) {
                        DictVal = dictData.getDictValue();
                        bl = true;
                        break;
                    }
                }
            }
            if (!bl) {
                DictVal = dict;
            }
        } else {
            DictVal = dict;
        }

        return DictVal;
    }

    private final String extractPath(TenantCategory category, Long daId) {
        StringBuilder path = new StringBuilder().append(category.getFondsCode()).append(File.separator).append(category.getCode()).append(File.separator).
                append(daId).append(File.separator);
        return path.toString();
    }

    private static final File getAbsoluteFile(String uploadDir, String fileName) throws IOException {
        File desc = new File(uploadDir + File.separator + fileName);

        if (!desc.exists()) {
            if (!desc.getParentFile().exists()) {
                desc.getParentFile().mkdirs();
            }
        }
        return desc.isAbsolute() ? desc : desc.getAbsoluteFile();
    }

    @Override
    public List<YqdaOnlineReception> selectYqdaOnlineReceptionList(YqdaOnlineReception onlineReception) {
        //查询状态是 0 和 -1 创建和审批不同意
        return onlineReceptionMapper.selectYqdaOnlineReceptionList(onlineReception);
    }

    @Override
    public int insertOnlineReception(YqdaOnlineReception onlineReception) {
        return onlineReceptionMapper.insertOnlineReception(onlineReception);
    }

    @Override
    public int updateYqdaOnlineReception(YqdaOnlineReception onlineReception) {
        return onlineReceptionMapper.updateYqdaOnlineReception(onlineReception);
    }

    @Override
    public YqdaOnlineReception getOnlineReceptionById(Long id) {
        return onlineReceptionMapper.getOnlineReceptionById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer fqjssp(Long[] ids) {
        for (int i = 0; i < ids.length; i++) {
            YqdaOnlineReception onlineReception1 = new YqdaOnlineReception();
            YqdaOnlineReception onlineReception2 = onlineReceptionMapper.getOnlineReceptionById(ids[i]);
            Map<String, Object> variables = new HashMap();
            variables.put("processVariables", onlineReception2.toProcessMap());
            R<ActivitiPackage> activitiPackageR = activitiService.startProcessWorkFlowArchiveOnlineReceive(variables);
            String activitiId = activitiPackageR.getData().getProcessInstance().getId();
            onlineReception1.setState(1);
            onlineReception1.setActivitiId(activitiId);
            onlineReception1.setId(ids[i]);
            onlineReceptionMapper.updateYqdaOnlineReception(onlineReception1);
        }
        return 1;
    }

    @Override
    public int killOnlineReceive(Long id) {
        YqdaOnlineReception yqdaOnlineReception = new YqdaOnlineReception();
        yqdaOnlineReception.setState(-1);
        yqdaOnlineReception.setId(id);
        return onlineReceptionMapper.updateYqdaOnlineReception(yqdaOnlineReception);
    }

    @Override
    @Transactional
    public int onlinereceiveBanjie(Long id) {
        //更新档案状态
        YqdaOnlineReception onlineReception = onlineReceptionMapper.getOnlineReceptionById(id);
        TenantCategory category = categoryMapper.selectTenantCategoryByID(onlineReception.getCategoryId(), new TenantCategory().getTableName());
        int state = 5;
        //更新项目
        if (category.getType() == 3) {
            yqItemMapper.updateStateByPackageId(state, new TenantYqItem().getTableName(), new OnlinePackageDa().getTableName(), id);
            archiveMapper.updateStateByPackageId(state, category.getItemTableName(), new OnlinePackageDa().getTableName(), 3, id);
        }
        //更新卷
        if (category.getType() == 3 || category.getType() == 1) {
            yqFolderMapper.updateStateByPackageId(state, new TenantYqFolder().getTableName(), new OnlinePackageDa().getTableName(), id);
            archiveMapper.updateStateByPackageId(state, category.getFolderTableName(), new OnlinePackageDa().getTableName(), 1, id);
        }
        //更新件
        yqdaMapper.updateStateByPackageId(state, new TenantYqda().getTableName(), new OnlinePackageDa().getTableName(), id);
        archiveMapper.updateStateByPackageId(state, category.getFileTableName(), new OnlinePackageDa().getTableName(), 0, id);
        //更新移交单
        YqdaOnlineReception yqdaOnlineReception = new YqdaOnlineReception();
        yqdaOnlineReception.setState(2);
        yqdaOnlineReception.setId(id);
        return onlineReceptionMapper.updateYqdaOnlineReception(yqdaOnlineReception);
    }

    @Override
    @Transactional
    public int deletePackage(Long id, int state) {
        YqdaOnlineReception onlineReception = onlineReceptionMapper.getOnlineReceptionById(id);
        if (onlineReception.getCategoryId() != null) {
            String tableCategory = new TenantCategory().getTableName();
            TenantCategory category = categoryMapper.selectTenantCategoryByID(onlineReception.getCategoryId(), tableCategory);
            if (category == null) {
                throw new ServiceException("门类信息不匹配!");
            }
            //删除项目
            if (category.getType() == 3) {
                OnlinePackageDa packageDa = new OnlinePackageDa();
                packageDa.setOnlineReceptionId(id);
                packageDa.setDaType(3);
                List<Long> list = onlinePackageDaMapper.getDaIdByPackageDaList(packageDa);
                if (list != null && list.size() > 0) {
                    List<List<Long>> lists = ListUtils.subList(list, 5000);
                    for (int j = 0; j < lists.size(); j++) {
                        List<Long> ids = lists.get(j);
                        yqItemMapper.delItemByIdList(new TenantYqItem().getTableName(), ids);
                        archiveMapper.delArchiveByIdList(category.getItemTableName(), ids);
                        itemFolderMapper.deleteItemFolderByItemId(String.join(",", ids.stream().map(Object::toString).collect(Collectors.toList())), new TenantItemFolder().getTableName());
                    }
                }
            }
            //删除卷
            if (category.getType() == 3 || category.getType() == 1) {
                OnlinePackageDa packageDa = new OnlinePackageDa();
                packageDa.setOnlineReceptionId(id);
                packageDa.setDaType(1);
                List<Long> list = onlinePackageDaMapper.getDaIdByPackageDaList(packageDa);
                if (list != null && list.size() > 0) {
                    List<List<Long>> lists = ListUtils.subList(list, 5000);
                    for (int j = 0; j < lists.size(); j++) {
                        List<Long> ids = lists.get(j);
                        yqFolderMapper.delFolderByIdList(new TenantYqFolder().getTableName(), ids);
                        archiveMapper.delArchiveByIdList(category.getFolderTableName(), ids);
                        yqdaFolderMapper.delYqdaFolderByFolderIds(String.join(",", ids.stream().map(Object::toString).collect(Collectors.toList())), new TenantYqdaFolder().getTableName());
                    }
                }
            }
            //删除件
            OnlinePackageDa packageDa = new OnlinePackageDa();
            packageDa.setOnlineReceptionId(id);
            packageDa.setDaType(0);
            List<Long> list = onlinePackageDaMapper.getDaIdByPackageDaList(packageDa);
            if (list != null && list.size() > 0) {
                List<List<Long>> lists = ListUtils.subList(list, 5000);
                for (int j = 0; j < lists.size(); j++) {
                    List<Long> ids = lists.get(j);
                    yqdaMapper.delYqdaByIdList(new TenantYqda().getTableName(), ids);
                    archiveMapper.delArchiveByIdList(category.getFileTableName(), ids);
                }
            }
            //删除电子文件
            OnlinePackageDa eFileDa = new OnlinePackageDa();
            eFileDa.setOnlineReceptionId(id);
            eFileDa.setDaType(2);
            List<Long> eFileList = onlinePackageDaMapper.getDaIdByPackageDaList(eFileDa);
            if (eFileList != null && eFileList.size() > 0) {
                List<List<Long>> lists = ListUtils.subList(eFileList, 5000);
                for (int j = 0; j < lists.size(); j++) {
                    List<Long> ids = lists.get(j);
                    tenantYqdaDocumentMapper.delDocByIdList(category.getEfileTableName(), ids);
                }
            }
        }
        //移交单
        YqdaOnlineReception updateOnlineReception = new YqdaOnlineReception();
        updateOnlineReception.setId(id);
        updateOnlineReception.setState(state);  //更新状态
        return onlineReceptionMapper.updateYqdaOnlineReception(updateOnlineReception);
    }

    @Override
    public int saveSiXingResult(Long id, Long siXingId, String siXingResult) {
        YqdaOnlineReception select = onlineReceptionMapper.getOnlineReceptionById(id);
        if (select.getSiXingResult() != null && "通过".equals(select.getSiXingResult())) {
            throw new ServiceException("数据已入库完成，不能二次入库");
        }
        YqdaOnlineReception onlineReception = new YqdaOnlineReception();
        onlineReception.setId(id);
        onlineReception.setSiXingId(siXingId);
        onlineReception.setSiXingResult(siXingResult);
        return onlineReceptionMapper.updateYqdaOnlineReception(onlineReception);
    }

    @Override
    public void sendPackageState(Long id, String result) {
        // 接口地址
        //String address = "http://127.0.0.1:9204/webservice/receiveFeedbackWebService?wsdl";
        String address = sysConfigService.selectConfigByKey("SyncJsStatePath");
        if (StringUtils.isNULLString(address)) {
            throw new ServiceException("系统参数SyncJsStatePath未配置，请配置系统参数！");
        }
        // 代理工厂
        JaxWsProxyFactoryBean jaxWsProxyFactoryBean = new JaxWsProxyFactoryBean();
        // 设置代理地址
        jaxWsProxyFactoryBean.setAddress(address);
        // 设置接口类型
        jaxWsProxyFactoryBean.setServiceClass(receiveFeedbackWebService.class);
        receiveFeedbackWebService feedbackWebService = (receiveFeedbackWebService) jaxWsProxyFactoryBean.create();

        YqdaOnlineReception onlineReception = onlineReceptionMapper.getOnlineReceptionById(id);
        if (org.apache.commons.lang3.StringUtils.isNotBlank(onlineReception.getOldTenantCode())) {
            JSONObject object = new JSONObject();
            object.put("IDENTIFIER", onlineReception.getBiaoShi());
            object.put("RESULT", result);
            object.put("RESULT", result);
            object.put("tenantCode", onlineReception.getOldTenantCode());
            JSONArray array = new JSONArray();
            array.add(object);
            feedbackWebService.receiveFeedback(array.toJSONString());
        }
    }
    private JSONArray objecttoarray(Object object) {
        if(object instanceof JSONObject){
            JSONArray array=new JSONArray(1);
            array.add(object);
            return array;
        }else if(object instanceof JSONArray){
            return (JSONArray)object;
        }
        return null;
    }

}
